<template>
    <div class="sys-role-edit-modal relative" ref="editAddModal" >
        <a-modal 
                v-model:open="state.isShow"
                width="700px"
                wrapClassName="custom-modal"
                :bodyStyle="{height:'500px',overflowY:'overlay',overflowX:'hidden',paddingRight:'6px'}"
                :title="state.formState.id != undefined && state.formState.id > 0? '编辑角色':'添加角色'" 
                :getContainer="() => $refs.editAddModal"
        >
                <template #footer>
                    <a-popconfirm
                        title="分配菜单后需重新分配按钮权限"
                        ok-text="确定"
                        cancel-text="取消"
                        @confirm="handleOk"
                    >
                        <a-button type="primary" :loading="state.loading">
                            确定
                        </a-button>
                    </a-popconfirm>
                    
                    <a-button type="link" @click="handleCancel">
                        取消
                    </a-button>
                </template>
                <a-form
                    ref="formRef"
                    :model="state.formState"
                    name="role-edit-form"
                    autocomplete="off"
                    :label-col="{ span: 6 }"
                    :wrapper-col="{ span: 18 }"
                >
                    <a-spin :spinning="state.loading">
                        <a-row >
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                                <a-form-item
                                    label="角色名称"
                                    name="name"
                                    :label-col="{ span: 3 }"
                                    :wrapper-col="{ span: 21 }"
                                    :rules="[{ required: true, message: '角色名称不能为空', trigger: 'blur' }]"
                                >
                                    <a-input v-model:value="state.formState.name" />
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                                <a-form-item
                                    label="角色编码"
                                    name="code"
                                    :label-col="{ span: 3 }"
                                    :wrapper-col="{ span: 21 }"
                                    :rules="[{ required: true, message: '角色编码不能为空', trigger: 'blur' }]"
                                >
                                    <a-input v-model:value="state.formState.code" :disabled="state.formState.id != undefined && state.formState.code == 'sys_admin'"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="排序"
                                    name="orderNo"
                                >
                                    <a-input-number class="w-full" v-model:value="state.formState.orderNo" placeholder="排序"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <a-form-item
                                    label="状态"
                                    name="status"
                                >
                                    <a-radio-group v-model:value="state.formState.status">
                                        <a-radio :value="1">启用</a-radio>
                                        <a-radio :value="2">禁用</a-radio>
                                    </a-radio-group>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                                <a-form-item
                                    label="备注"
                                    name="remark"
                                    :label-col="{ span: 3 }"
                                    :wrapper-col="{ span: 21 }"
                                >
                                    <a-textarea :rows="2" v-model:value="state.formState.remark"/>
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                                <a-form-item
                                    label="菜单权限"
                                    :label-col="{ span: 3 }"
                                    :wrapper-col="{ span: 21 }"
                                >
                                    <!-- <a-button @click="state.checkStrictly = !state.checkStrictly">
                                        {{ state.checkStrictly ? '取消关联' : '关联菜单' }}
                                    </a-button> -->
                                    <a-tree
                                        v-model:expandedKeys="state.expandedKeys"
                                        v-model:selectedKeys="state.selectedKeys"
                                        v-model:checkedKeys="state.checkedKeys"
                                        :checkStrictly="state.checkStrictly"
                                        checkable
                                        :tree-data="state.menuData"
                                        :field-names="{key:'id'}"
                                        @check="handleChecked"
                                    >
                                        <template #title="{ title, key,type }">
                                            <span v-if="type != 3">{{ title }}</span>
                                            <span v-else class="button-node-wrapper"> {{ title }}</span>
                                        </template>
                                    </a-tree>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-spin>
                </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { reactive,onMounted,ref } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { apiSysMenuListGet } from '@/api/sys/sysMenu';
import type { ResType } from '@/api/types';
import { apiSysRoleAddPost, apiSysRoleOwnMenuListGet, apiSysRoleUpdatePost } from '@/api/sys/sysRole';
import type { TreeProps } from 'ant-design-vue';
import { cloneDeep } from 'lodash';
import { emitter, showMsg } from '@/utils';
const emits = defineEmits<{
    (e:"handleQuery"):void
}>()
const formRef = ref<FormInstance>()
const editAddModal = ref()

const state = reactive({
    isShow:false,
    formState:{} as any,
    menuData:[] as any,
    menuDataOrigin:[] as any[],
    expandedKeys:[] as TreeProps['treeData'],
    selectedKeys:[] as TreeProps['selectedKeys'],
    checkedKeys:[] as TreeProps['checkedKeys'],
    loading:true,
    checkStrictly:false,
    oneMenuIds:[] as any[], //目录id
    twoMenuIds:[] as any[], //菜单id
})

const handleOk = async ()=>{
    try{
        state.loading = true
        await formRef.value?.validate()
        const submitData = cloneDeep(state.formState)
        submitData.menuIdList = state.checkedKeys
        if(state.formState.id != undefined && state.formState.id > 0){
            await apiSysRoleUpdatePost(submitData)
            showMsg('修改成功','success')
            emitter.emit("update-role-btn-auth",state.formState)
        }else {
            await apiSysRoleAddPost(submitData)
            showMsg('添加成功','success')
        }
        handleCancel()
        emits('handleQuery')
        emitter.emit('posOrRoleUpdate') //更新用户列表缓存
    }finally{
        state.loading = false
    }
}

const handleCancel = async ()=>{
    state.isShow = false
    state.formState = {}
    state.menuData = []
    state.expandedKeys = []
    state.selectedKeys = []
    state.checkedKeys = []
    state.oneMenuIds = [] //目录id
    state.twoMenuIds = [] //菜单id
}

const handleGenExpandKeys = (data:any[])=>{
    data.forEach((item:any)=>{
        if(item.type != 3){
            state.expandedKeys?.push(item.id)
        }
        if(Array.isArray(item.children) && item.children?.length > 0){
            handleGenExpandKeys(item.children)
        }
    })
}

// 过滤按钮数据，保留原始层级结构
const formateMenuData = (data: any[]) => {
    // 深拷贝避免修改原始数据
    const cloneData = JSON.parse(JSON.stringify(data));
    const filterButtons = (items: any[]) => {
        // 过滤出非按钮项
        const filtered = items.filter(item => item.type !== 3);
        // 递归处理每个非按钮项的子项
        filtered.forEach(item => {
            if(item.type == 1){
                state.oneMenuIds.push(item.id)
            }else if(item.type == 2){
                state.twoMenuIds.push(item.id)
            }
            if (Array.isArray(item.children) && item.children.length > 0) {
                // 对每个子项数组递归应用过滤函数
                item.children = filterButtons(item.children);
                
                // 如果过滤后子项数组为空，删除children属性
                if (item.children.length === 0) {
                    delete item.children;
                }
            }
        });
        return filtered;
    };
    return filterButtons(cloneData);
};

// 过滤出菜单id
const filterMapCheckedIds = (data:any[])=>{
    let ids:any[] = []
    data.forEach(id=>{
        // 菜单
        if(state.twoMenuIds.includes(id)){
            ids.push(id)
        }
    })
    return ids
}

const handleOpen = async (row:any)=>{
    // 分配菜单权限，同时处理角色权限目录选中情况，菜单中新增一个菜单，再次编辑的时候会被激活情况
    state.isShow = true
    state.loading = true
    // 获取所有菜单展示
    let res = await apiSysMenuListGet({tenantId:row.tenantId}) as ResType<any>
    state.menuDataOrigin = res.data.result ?? []
    state.menuData = formateMenuData(state.menuDataOrigin)

    handleGenExpandKeys(state.menuDataOrigin)

    state.formState = JSON.parse(JSON.stringify(row))
    if(row.id != undefined){
        // 获取当前角色拥有角色id
        res = await apiSysRoleOwnMenuListGet(row.id)
        state.checkedKeys = filterMapCheckedIds(res.data.result)
    }
    state.loading = false
    formRef.value?.clearValidate()
}

const handleChecked = (checkedKeys:any[],e:any)=>{
    console.log(checkedKeys,e);
    state.checkedKeys = checkedKeys
    // state.checkedKeys = {
    //     checked:checkedKeys,
    //     halfChecked:e.halfCheckedKeys
    // }
}

defineExpose({
    handleOpen
})
</script>

<style lang="scss" scoped>
:deep(.ant-form-item){
    margin-bottom: 20px;
} 
:deep(.anticon.anticon-caret-down){
    display: inline-flex;
}
:deep(.ant-tree-checkbox){
    margin-block-start: 0;
}


</style>